package com.ef.web.action;

import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.hibernate.Criteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;

import com.ef.constant.ConfirmMessage;
import com.ef.constant.ECallStatus;
import com.ef.constant.ELeadsEventType;
import com.ef.constant.ELeadsStatus;
import com.ef.constant.EUserTodoObject;
import com.ef.constant.EUserTodoStatus;
import com.ef.constant.EUserTodoType;
import com.ef.domain.Leads;
import com.ef.domain.LeadsDealHistory;
import com.ef.domain.LeadsEventHistory;
import com.ef.domain.User;
import com.ef.domain.UserTodoEvent;
import com.ef.service.LeadsDealHistoryService;
import com.ef.service.LeadsEventHistoryService;
import com.ef.service.TodoEventService;
import com.ef.util.CalendarUtil;
import com.ef.util.CustomExample;
import com.ef.util.LeadsExample;

public class TMAction extends LeadsAction {

	private static final long serialVersionUID = 1L;

	//private LeadsEventHistoryService leadsEventHistoryService;
	
	//private LeadsDealHistoryService leadsDealHistoryService;

//	public LeadsDealHistoryService getLeadsDealHistoryService() {
//		return leadsDealHistoryService;
//	}
//
//	public void setLeadsDealHistoryService(
//			LeadsDealHistoryService leadsDealHistoryService) {
//		this.leadsDealHistoryService = leadsDealHistoryService;
//	}

	public List<LeadsDealHistory> getDeals() {
		return deals;
	}

	public void setDeals(List<LeadsDealHistory> deals) {
		this.deals = deals;
	}

	private TodoEventService todoEventService;

	//private List<LeadsEventHistory> calls;
	
	private List<LeadsDealHistory> deals;

	private Long currentCallId;

	private String currentCallTelephone;

	private Date currentCallDealTime;

	private ECallStatus currentCallStatus = ECallStatus.Connected;

	private String currentCallComments;

	private Long todoEventId;

	private EUserTodoType todoEventType;

	private String todoEventComments;

	private Date todoEventDate;

	private String caller;

	private String todoEventTime;

	private Date selTodoStartTime;

	public Date getSelTodoStartTime() {
		return selTodoStartTime;
	}

	public void setSelTodoStartTime(Date selTodoStartTime) {
		this.selTodoStartTime = selTodoStartTime;
	}

	public Date getSelTodoEndTime() {
		return selTodoEndTime;
	}

	public void setSelTodoEndTime(Date selTodoEndTime) {
		this.selTodoEndTime = selTodoEndTime;
	}

	private Date selTodoEndTime ;

	private String tel;

	private String[] selLeadsStatus;

	/**
	 * 没有CC的帐号
	 */
	private boolean noCc = true;

	/**
	 * 所有用户的帐号
	 */
	private boolean allUser = false;

	private Integer pagesize = 60;

	public Integer getPagesize() {
		return pagesize;
	}

	public void setPagesize(Integer pagesize) {
		this.pagesize = pagesize;
	}

	public boolean isNoCc() {
		return noCc;
	}

	public void setNoCc(boolean noCc) {
		this.noCc = noCc;
	}

	public boolean isAllUser() {
		return allUser;
	}

	public void setAllUser(boolean allUser) {
		this.allUser = allUser;
	}

	public String[] getSelLeadsStatus() {
		return selLeadsStatus;
	}

	public void setSelLeadsStatus(String[] selLeadsStatus) {
		this.selLeadsStatus = selLeadsStatus;
	}

	public TMAction() {

	}

	private static SimpleDateFormat timeDf = new SimpleDateFormat("K:mm a",
			new Locale("en"));

	@SuppressWarnings("serial")
	public String list() {
		fetchListData();
		CustomExample<Leads> example = new LeadsExample(this.getModel(),
				Leads.class) {
			public void appendCondition(Criteria criteria) {
				super.appendCondition(criteria);
				if (selTmCall!=null){
				    criteria.add(Restrictions.eq("tmCall",selTmCall));
				}
				User user = getSessionUser();
				if (noCc) {// 没有Cc
					if (allUser) {
						criteria.add(Restrictions.isNotNull("tm"));
						criteria.add(Restrictions.isNull("cc"));
					} else {
						if (user.getRole() != null
								&& user.getRole().getName().equalsIgnoreCase(
										"TM")) {
							criteria.createCriteria("tm").add(
									Restrictions.eq("id", getSessionUser()
											.getId()));
						} else {
							criteria.add(Restrictions.isNotNull("tm"));
						}
						criteria.add(Restrictions.isNull("cc"));
					}
				} else {// 全部信息
					if (allUser) {
						criteria.add(Restrictions.isNotNull("tm"));
						criteria.add(Restrictions.isNotNull("cc"));
					} else {
						if (user.getRole() != null
								&& user.getRole().getName().equalsIgnoreCase(
										"TM")) {
							criteria.createCriteria("tm").add(
									Restrictions.eq("id", getSessionUser()
											.getId()));
						} else {
							criteria.add(Restrictions.isNotNull("tm"));
						}
						criteria.add(Restrictions.isNotNull("cc"));
					}
				}
				if (selLeadsStatus != null && selLeadsStatus.length > 0) {
					Disjunction or = Restrictions.disjunction();
					Property myProperty = Property.forName("leadsStatus");
					for (String mid : selLeadsStatus) {
						if (mid!=null&&!mid.equals("")){
						  or.add(myProperty.eq(ELeadsStatus.valueOf(mid)));
						}
					}
					criteria.add(or);
				}
				criteria.addOrder(Order.desc("updateTime"));
			}
		};
		example.addBetweenDateProperty("createTime", selCreateStartTime,
				selCreateEndTime);
		example.addBetweenDateProperty("setApptTime", selSetApptStartTime,
				selSetApptEndTime);
		example.addBetweenDateProperty("showTime", selShowStartTime,
				selShowEndTime);
		example.addBetweenDateProperty("lastEventTime", selLastTouchStartTime,
				selLastTouchEndTime);
		example.addBetweenDateProperty("payTime", selPayStartTime,
				selPayEndTime);
		example.addBetweenDateProperty("tmAssignTime", selAssignTmStartTime,
				selAssignTmEndTime);
		example.addBetweenDateProperty("nextEventTime", selTodoStartTime,
				selTodoEndTime);
		this.listResult = leadsService.findByExample(example, this
				.getStartIndex(), pagesize);
		return LIST;
	};

	private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

	public String saveCall() {
		Leads leads = this.saveLeads();
		if (leads == null) {
			this.setResult(ConfirmMessage.MSG_SAVELEADS_ERROR);
			fetchListData();
			calls = leadsEventHistoryService.findByLeads(leads);
			return CALL;
		}
		Date todoEventDatetime=null;
		if (todoEventDate != null) { // todoEventDate 不为空处理
			Date time = null;
			if (todoEventTime != null && todoEventTime.trim().length() > 0) {
				try {
					time = timeDf.parse(todoEventTime);
				} catch (ParseException e) {
					System.out.println("TodoEventAction parse time error");
				}
			}
			if (time == null) {
				try {
					time = timeDf.parse("9:00 AM");
				} catch (ParseException e) {
					System.out.println("TodoEventAction parse time error");
				}
			}
			todoEventDatetime=CalendarUtil.getDateTime(todoEventDate,time);
		}
		if (currentCallTelephone != null
				&& currentCallTelephone.trim().length() > 0) {
			LeadsEventHistory currentCall = null;
			if (currentCallId == null) {
				currentCall = new LeadsEventHistory();
				leads.setTmCall(leads.getTmCall() + 1);
			} else {
				currentCall = leadsEventHistoryService.findById(currentCallId);
			}
 			currentCall.setComments(currentCallComments);
			currentCall.setCallStatus(currentCallStatus);
			currentCall.setDealTime(new Date());
			currentCall.setEventType(ELeadsEventType.TMCall);
			currentCall.setLeads(leads);
			currentCall.setTelephone(currentCallTelephone.trim());
			currentCall.setOperater(getSessionUser());
			currentCall.setNextCallTime(todoEventDatetime);
			leadsEventHistoryService.saveOrUpdate(currentCall);
			currentCallId=currentCall.getId();
			leads.setLastEventTime(new Date());
			leads.setLastEventCommons(currentCallComments.trim().equals("") ? leads
							.getLastEventCommons()
							: currentCallComments);
		}
		if (todoEventDate != null) { // todoEventDate 不为空处理
			String day = df.format(todoEventDate);
			String title = "NOTE:" + day + " " + todoEventTime + " call "
					+ leads.getName();
			UserTodoEvent todoEvent = null;
			if (todoEventId == null) {
				todoEvent = new UserTodoEvent();
			} else {
				todoEvent = todoEventService.findById(todoEventId);
			}
			todoEvent.setCreateTime(new Date());
			todoEvent.setTodoType(todoEventType);
			todoEvent.setCreateUser(getSessionUser());
			todoEvent.setGoAction("/customer/TM/call?id=" + leads.getId());
			Date time = null;
			if (todoEventTime != null && todoEventTime.trim().length() > 0) {
				try {
					time = timeDf.parse(todoEventTime);
				} catch (ParseException e) {
					System.out.println("TodoEventAction parse time error");
				}
			}
			if (time == null) {
				try {
					time = timeDf.parse("9:00 AM");
				} catch (ParseException e) {
					System.out.println("TodoEventAction parse time error");
				}
			}
			todoEvent.setReminderEndTime(CalendarUtil.getDateTime(
					todoEventDate, time));
			time.setTime(time.getTime() - 30 * 60 * 1000);
			todoEvent.setReminderStartTime(CalendarUtil.getDateTime(
					todoEventDate, time));
			todoEvent.setSelLeads(leads);
			todoEvent.setToObject(EUserTodoObject.MySelf);
			todoEvent.setStatus(EUserTodoStatus.Valid);
			todoEvent.setToUser(getSessionUser());
			todoEvent.setDetail(todoEventComments);
			todoEvent.setTitle(title);
			todoEventService.saveOrUpdate(todoEvent);
			todoEventId=todoEvent.getId();
		}
		if (todoEventDatetime!=null){
			   leads.setNextEventTime(todoEventDatetime);
		}
		leadsService.saveOrUpdate(leads);
		fetchListData();
		calls = leadsEventHistoryService.findByLeads(leads);
		deals=leadsDealHistoryService.findShowHistoryByLeads(leads);
		this.setResult(ConfirmMessage.Call);
		return CALL;
	}

	public String call() {
		fetchListData();
		caller = getSessionUser().getTelCode();
		if (this.getModel() != null && this.getModel().getId() != null) {
			calls = leadsEventHistoryService.findByLeads(this.getModel());
			deals=leadsDealHistoryService.findShowHistoryByLeads(this.getModel());
		}
		
		return CALL;
	}

	public String callFromCallCenter() {
		String urlStr = "http://192.168.5.166/manager/makecall.php?caller="
				+ caller + "&callee=" + tel;
		try {
			URL hp = new URL(urlStr);
			URLConnection hpCon = hp.openConnection();
			// 要取一下
			hpCon.getDate();
		} catch (Exception err) {
			System.out.print("callFromCallCenter error:" + err.getMessage());
		}
		return null;
	}

	public Boolean isTMOwner(Long tmid){
		User user=getSessionUser();
		if (user.getRole().getName().trim().equalsIgnoreCase("TM")){
			 if (user.getId().equals(tmid)){
				 return true;
			 }else{
				 return false;
			 }
		}
		return true;
	}
//	public List<LeadsEventHistory> getCalls() {
//		return calls;
//	}
//
//	public void setCalls(List<LeadsEventHistory> calls) {
//		this.calls = calls;
//	}

//	public LeadsEventHistoryService getLeadsEventHistoryService() {
//		return leadsEventHistoryService;
//	}
//
//	public void setLeadsEventHistoryService(
//			LeadsEventHistoryService leadsEventHistoryService) {
//		this.leadsEventHistoryService = leadsEventHistoryService;
//	}

	public TodoEventService getTodoEventService() {
		return todoEventService;
	}

	public void setTodoEventService(TodoEventService todoEventService) {
		this.todoEventService = todoEventService;
	}

	public Long getCurrentCallId() {
		return currentCallId;
	}

	public void setCurrentCallId(Long currentCallId) {
		this.currentCallId = currentCallId;
	}

	public String getCurrentCallTelephone() {
		return currentCallTelephone;
	}

	public void setCurrentCallTelephone(String currentCallTelephone) {
		this.currentCallTelephone = currentCallTelephone;
	}

	public ECallStatus getCurrentCallStatus() {
		return currentCallStatus;
	}

	public void setCurrentCallStatus(ECallStatus currentCallStatus) {
		this.currentCallStatus = currentCallStatus;
	}

	public Long getTodoEventId() {
		return todoEventId;
	}

	public void setTodoEventId(Long todoEventId) {
		this.todoEventId = todoEventId;
	}

	public EUserTodoType getTodoEventType() {
		return todoEventType;
	}

	public void setTodoEventType(EUserTodoType todoEventType) {
		this.todoEventType = todoEventType;
	}

	public String getTodoEventComments() {
		return todoEventComments;
	}

	public void setTodoEventComments(String todoEventComments) {
		this.todoEventComments = todoEventComments;
	}

	public Date getTodoEventDate() {
		return todoEventDate;
	}

	public void setTodoEventDate(Date todoEventDate) {
		this.todoEventDate = todoEventDate;
	}

	public String getCurrentCallComments() {
		return currentCallComments;
	}

	public void setCurrentCallComments(String currentCallComments) {
		this.currentCallComments = currentCallComments;
	}

	public Date getCurrentCallDealTime() {
		return currentCallDealTime;
	}

	public void setCurrentCallDealTime(Date currentCallDealTime) {
		this.currentCallDealTime = currentCallDealTime;
	}

	public String getTodoEventTime() {
		return todoEventTime;
	}

	public void setTodoEventTime(String todoEventTime) {
		this.todoEventTime = todoEventTime;
	}

	public String getCaller() {
		return caller;
	}

	public void setCaller(String caller) {
		this.caller = caller;
	}

	public String getTel() {
		return tel;
	}

	public void setTel(String tel) {
		this.tel = tel;
	}

}
